package von.seiji.cn.test;

import org.junit.Test;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class 三种定时区别 {

    @Test
    public void alfkdj() throws InterruptedException {
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(3);
        ScheduledFuture<?> future = threadPool.schedule(() -> {
            System.out.println("你好");
        }, 1, TimeUnit.SECONDS);
        threadPool.shutdown();
        threadPool.awaitTermination(3, TimeUnit.SECONDS);
    }

        public static void main(String[] args) {
            ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
            ScheduledFuture<?> schedule = executor.schedule(() -> {
//            executor.shutdown();
                System.out.println("hello!!!");
            }, 30, TimeUnit.SECONDS);

            //和scheduleAtFixedRate类似
            Timer timer = new Timer("普通的定时");
            timer.schedule(new TimerTask(){
                @Override
                public void run() {

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {}
                    System.out.println("schedule:" + System.currentTimeMillis());
                }
            }, 1000, 3000);

//        ScheduledExecutorService  executor = Executors.newScheduledThreadPool(1);
            //执行run中的休眠时间不超过线程设置的执行间隔时间前提下，线程执行间隔为设置的执行间隔
            ScheduledFuture<?> scheduledFuture = executor.scheduleAtFixedRate(() -> {
                System.out.println("scheduleAtFixedRate:" + System.currentTimeMillis());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {}
            }, 1, 3, TimeUnit.SECONDS);

            //线程执行间隔为设置的执行间隔加上run中的休眠时间
            executor.scheduleWithFixedDelay(() -> {
                System.out.println("scheduleWithFixedDelay:" + System.currentTimeMillis());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {}
            }, 1, 3, TimeUnit.SECONDS);
        }

}
